package com.simple.util;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

public class ExportExecl {



    public static void exportData(List<Map<String,Object>> data, Workbook workbook, String page) throws Exception{

        int i=0;
        for(Map<String,Object> map : data){
            String img_name = (String)map.get("img_name");
            String is_valid = (String)map.get("is_valid");
            String is_success = (String)map.get("is_success");
            String is_point = (String)map.get("is_point");
            int serach_pos = -1;
            if(null != map.get("search_pos")){
                serach_pos = (int)map.get("search_pos");
            }

            long question_id = -1;
            if(null != map.get("question_id")){
                question_id = (long)map.get("question_id");
            }

            String is_mark = (String)map.get("is_mark");

            Sheet sheet = workbook.getSheet(page);
            Row row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(img_name);
            row.createCell(1).setCellValue(is_valid);
            row.createCell(2).setCellValue(is_success);
            row.createCell(3).setCellValue(is_point);
            row.createCell(4).setCellValue(serach_pos);
            row.createCell(5).setCellValue(question_id);
            row.createCell(6).setCellValue(is_mark);
            i++;
        }
    }


    public static void exportTitle(String[] titles,Workbook workbook,String page) throws Exception{
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        Sheet sheet = workbook.createSheet(page);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        Row row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        CellStyle cellStyle = workbook.createCellStyle();
        //居中样式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        Cell cell = null;
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i);//列索引从0开始
            cell.setCellValue(titles[i]);//列名1
            cell.setCellStyle(cellStyle);//列居中显示
        }
    }

    public static void export(Workbook workbook,String[] titles,List<Map<String,Object>> data,String page) throws Exception{
        // 第七步，将文件输出到客户端浏览器
        try {
            // 第一步，创建一个workbook，对应一个Excel文件
            //Workbook workbook = new XSSFWorkbook();
            exportTitle(titles,workbook,page);
            ExportExecl.exportData(data,workbook,page);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
